<template>
  <div class="app-container">
    <div class="mainbox">
      <div class="filter-container">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams"
                 :inline="true" label-width="68px" @submit.native.prevent>
          <el-form-item label="类型名称" prop="typeName">
            <el-input
              v-model.trim="queryParams.typeName"
              maxlength="30"
              class="filter-item limit"
              placeholder="请输入内容"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="分类类型" prop="classify">
            <el-select v-model="queryParams.classify" clearable placeholder="请选择">
              <el-option
                v-for="dict in dict.type.messageType"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发送渠道" prop="channelId">
            <el-select v-model="queryParams.channelId" value-key="channelId" clearable
                       placeholder="请选择">
              <el-option
                v-for="item in channelList"
                :key="item.channelId"
                :label="item.channelName"
                :value="item.channelId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <div>
          <div class="flex-1" />
          <div style="display:flex;">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </div>
        </div>
      </div>
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button
            v-permission="['MESSAGETYPE_ADD_BUTTON']"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
          >新增</el-button>
          <div class="flex-1" />
          <dt-dialog-column v-model="isShowTable" :columns="showColumns" :table-ref="$refs.table"
                            @queryTable="getList" />
        </div>
        <el-table v-if="isShowTable" ref="table" v-loading="loading"
                  border highlight-current-row :header-cell-style="{ backgroundColor: '#f2f2f2'}"
                  :data="MessageTypeList">
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            :index="(index)=>(queryParams.pageNo - 1) * queryParams.pageSize + index + 1"
          />
          <el-table-column v-if="showColumns[0].show" key="typeCode" label="类型编码"
                           show-overflow-tooltip align="center" prop="typeCode" />
          <el-table-column v-if="showColumns[1].show" key="typeName" label="类型名称"
                           show-overflow-tooltip align="center" prop="typeName" />
          <el-table-column v-if="showColumns[2].show" key="classify" label="分类类型"
                           show-overflow-tooltip align="center" prop="classify">
            <template slot-scope="scope">
              <dt-dict-tag :options="dict.type.messageType" :value="scope.row.classify" />
            </template>
          </el-table-column>
          <el-table-column v-if="showColumns[3].show" key="priorityLevel" label="优先级"
                           show-overflow-tooltip align="center" prop="priorityLevel">
            <template slot-scope="scope">
              <dt-dict-tag :options="dict.type.classifyLevel" :value="scope.row.priorityLevel" />
            </template>
          </el-table-column>
          <el-table-column v-if="showColumns[4].show" key="channelName" label="发送渠道"
                           show-overflow-tooltip align="center" prop="channelName">
                           <!-- <template slot-scope="scope">{{ getChannelId(scope.row) }}</template> -->
          </el-table-column>
          <el-table-column v-if="showColumns[5].show" key="remark" label="备注"
                           show-overflow-tooltip align="center" prop="remark" />
          <el-table-column v-if="showColumns[6].show" key="createTime" label="创建时间"
                           show-overflow-tooltip align="center" prop="createTime"
                           width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="showColumns[7].show" key="updateTime" label="修改时间"
                           show-overflow-tooltip align="center" prop="updateTime"
                           width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column :key="Math.random()" label="操作" fixed="right"
                           align="center" class-name="small-padding fixed-width" width="190">
            <template slot-scope="scope">
              <el-button
                v-permission="['MESSAGETYPE_UPDATE_BUTTON']"
                size="small"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                v-permission="['MESSAGETYPE_DEL_BUTTON']"
                :disabled="handleIsDisabled(scope.row)"
                size="small"
                icon="el-icon-delete"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <dt-pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNo"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 添加或修改消息类型对话框 -->
    <dt-dialog :title="title" :visible.sync="open" :is-loading="loading"
               @comfirmBtn="submitForm" @closeDialog="cancel">
      <div slot="content">
        <el-form ref="form" :model="form" :rules="rules"
                 label-width="84px">
          <el-form-item label="类型名称" prop="typeName">
            <el-input v-model.trim="form.typeName" placeholder="请输入类型名称" maxlength="30"
                      show-word-limit class="limit" />
          </el-form-item>
          <el-form-item label="类型编码" prop="typeCode">
            <el-input v-model.trim="form.typeCode" placeholder="请输入类型编码" maxlength="30"
                      show-word-limit class="limit" />
          </el-form-item>
          <el-form-item label="分类类型" prop="classify">
            <el-select v-model="form.classify" clearable placeholder="请选择分类类型"
                       style="width:100%;">
              <el-option
                v-for="dict in dict.type.messageType"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优先级" prop="priorityLevel">
            <el-select v-model="form.priorityLevel" clearable placeholder="请选择优先级"
                       style="width:100%;">
              <el-option
                v-for="dict in dict.type.classifyLevel"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发送渠道" prop="channelId">
            <el-select v-model="channelId" value-key="channelId" clearable
                       placeholder="请选择发送渠道" style="width:100%;" multiple>
              <el-option
                v-for="item in channelList"
                :key="item.channelId"
                :label="item.channelName"
                :value="item.channelId"
                :style="{color:item.bgColor}"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model.trim="form.remark" type="textarea" placeholder="请输入备注"
                      maxlength="200" show-word-limit class="limit" />
          </el-form-item>
        </el-form>
      </div>
    </dt-dialog>
  </div>
</template>

<script>
import { listMessageType, getMessageType, delMessageType, addMessageType, updateMessageType, listChannelType } from '@/framework/api/messageType/MessageType'
import { uuId } from '@/framework/utils/uuid'
import { checkCode, checkChar } from '@/framework/utils/validate'

export default {
  name: 'MessageType',
  dicts: ['messageType', 'classifyLevel', 'wayType'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显隐表格
      isShowTable: true,
      // 选中数组
      ids: [],
      // 列显隐数组
      showColumns: [
        { prop: 'typeCode', label: '类型编码', show: true },
        { prop: 'typeName', label: '类型名称', show: true },
        { prop: 'classify', label: '分类类型', show: true },
        { prop: 'priorityLevel', label: '优先级', show: true },
        { prop: 'channelName', label: '发送渠道', show: true },
        { prop: 'remark', label: '备注', show: true },
        { prop: 'createTime', label: '创建时间', show: true },
        { prop: 'updateTime', label: '修改时间', show: true }
      ],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息类型表格数据
      MessageTypeList: [],
      // 渠道类型数据
      channelList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        typeName: null,
        classify: null,
        channelId: null
      },
      // 表单参数
      form: {
        typeId: null,
        typeName: null,
        typeCode: null,
        classify: null,
        priorityLevel: '2',
        remark: null
      },
      channelId: [],
      // 表单校验
      rules: {
        typeName: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('类型名称不能为空'))
              } else if (!checkChar(value)) {
                callback(new Error('请输入汉字、字母、数字或下划线'))
              } else {
                callback()
              }
            } }
        ],
        typeCode: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('类型编码不能为空'))
              } else if (!checkCode(value)) {
                callback(new Error('请输入字母、数字或下划线'))
              } else {
                callback()
              }
            } }
        ],
        classify: [
          { required: true, message: '分类类型不能为空', trigger: 'change' }
        ],
        priorityLevel: [
          { required: true, message: '优先级不能为空', trigger: 'change' }
        ],
        channelId: [
          { required: true,
            trigger: 'change',
            // message: '发送渠道不能为空'
            validator: (rule, value, callback) => {
              if (this.channelId.length <= 0) {
                callback(new Error('发送渠道不能为空'))
              } else {
                callback()
              }
            }
          }
        ]
      }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.getList()
      this.getChannelList()
    },
    /** 查询消息类型列表 */
    getList() {
      this.loading = true
      listMessageType(this.queryParams).then(({ data: response }) => {
        this.MessageTypeList = response.rows
        this.total = response.totalRows
        this.loading = false
      })
    },
    // 查询渠道类型
    getChannelList() {
      listChannelType().then((res) => {
        this.channelList = res.data
        this.channelList.forEach((item) => {
          item.statusFlag === 'Y' ? item.bgColor = '#67c23a' : item.bgColor = '#f56c6c'
        })
      })
    },
    // 取消按钮
    cancel() {
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        typeId: null,
        typeName: null,
        typeCode: null,
        classify: null,
        priorityLevel: '2',
        remark: null
      }
      this.channelId = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getChannelList()
      this.form.typeCode = uuId(8)
      this.open = true
      this.title = '新增类型'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getChannelList()
      getMessageType(row.typeId).then((response) => {
        this.form = response.data
        if (response.data.channelId != null && response.data.channelId.length) {
          this.channelId = response.data.channelId.split(',')
        }
        this.open = true
        this.title = '修改类型'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.channelId = this.channelId.join(',')
          if (this.form.typeId != null) {
            updateMessageType(this.form).then((response) => {
              this.$dtModal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMessageType(this.form).then((response) => {
              this.$dtModal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$dtModal.confirm(`是否确认删除消息类型编号为"${row.typeName}"的数据项？`).then(() => {
        return delMessageType(row.typeId)
      }).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleIsDisabled(data) {
      const arr = ['lockMailCode', 'emailVerificationCode', 'smsVerificationCode', 'initPasswordSms', 'initPasswordEmail', 'employeeNotice', 'workflowType', 'timerType']
      if (arr.includes(data.typeCode)) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>
